/** Bhumika Udani   23rd Dece 2010       v1.1  Batch job to update the account type to evergreen for the local advertiser accounts.
*   Bhumika Udani   17th April 2012      v1.2  Included assert check in test method to check for reduced coverage. Current test class coverage is 93%
*/

global class AccountTypeUpdate implements Database.Batchable<sObject>{
      
      public   String query;     
      public   String email;
      public   id     accountRecordType;
      Date currentdate = System.today();


    global database.querylocator start(Database.BatchableContext BC){       
        return Database.getQueryLocator(query);
    }
    
    
     global void execute(Database.BatchableContext BC, List<sObject> scope){   

          List<Account> Account = new List<Account>();      
          
           for(sObject s : scope){
             account acnt = (account)s;
             
             if(acnt.Renewal_Date__c < currentdate){
                if(acnt.Contract_Status__c == 'active' || acnt.Account_Status__c == 'Active') 
               try{
            	     acnt.Type__c = 'Evergreen';         
                	 	System.debug('Account type : ' + acnt.Type__c );
                	 Account.add(acnt);
                 		System.debug('Account type 00000000 : ' + acnt.Type__c );
                 }
               catch (exception ex){
                	 System.debug('Add account Fail : ' + ex);
                 }
             }
          }  
              try{
                  update Account;           
                 }
              catch (exception ex){
                 System.debug('Update account Fail : ' + ex);
                      }
                  }
             
             global void finish(Database.BatchableContext BC){   
           
                  AsyncApexJob aaj = [Select Id, Status, NumberOfErrors, CompletedDate, ApexClassID,JobItemsProcessed, TotalJobItems, CreatedBy.Email
                                      from AsyncApexJob where Id =:BC.getJobId()];

           
              String emailMessage = 'Your batch job ' + 'AccountOwnerReassignment ' + 'has finished.  It executed ' + aaj.totalJobItems   
                    + ' batches.  Of which, ' + aaj.jobitemsprocessed   
                     + ' processed without any exceptions thrown and '  
                      + aaj.numberOfErrors +  ' batches threw unhandled exceptions.' 
                            + '  Of the batches that executed without error, '  
                                 + ' records were not updated successfully.';  

     
             
             Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                     mail.setToAddresses(new String[] {email});        
                     mail.setReplyTo('bhumika.udani@accenture.com');        
                     mail.setSenderDisplayName('Batch Processing');        
                     mail.setSubject('Batch Process Completed');        
                     mail.setPlainTextBody(emailMessage);
                     mail.setHtmlBody(emailMessage);
              
                }
              
 static testMethod void testaccountTypeUpdate(){
 
         List <Account> AccountList = new List<Account>();
         Id accountRecordType = RecordTypeHelper.GetRecordTypeID('Account', 'Local OOR Customer');
         List<User> UserList = new List<User>();
         
         UserList = [select id from user where IsActive = true limit 2];
         date myPastDate = date.newInstance(2010, 12, 25);
         date myFutureDate = myPastDate.addDays(10); 
         
         account testAccount1 = new account();
         account testAccount2 = new account();
         
         testAccount1.ownerid = UserList[0].id ;
         testAccount1.RecordTypeId = accountRecordType;
         testAccount1.name = 'Test account1' ;
         testAccount1.phone = '56700948909' ;
         testAccount1.Contract_Status__c = 'Inactive' ;
         testAccount1.Account_Status__c = 'InActive' ;
         testAccount1.Renewal_Date__c = myPastDate ;
         testAccount1.AFrontier_CustomerID__c = '';

         testAccount2.ownerid = UserList[1].id;
         testAccount2.RecordTypeId = accountRecordType ;
         testAccount2.name = 'Test account2' ;
         testAccount2.phone = '56700008909' ;
         testAccount2.Contract_Status__c = 'inactive' ;
         testAccount2.Account_Status__c = 'Inactive' ;
         testAccount2.Renewal_Date__c = myPastDate;
         testAccount2.AFrontier_CustomerID__c = '09568574';
         
         AccountList.add(testAccount1);
         AccountList.add(testAccount2);
         
         insert AccountList;
         system.debug('AccountList' + AccountList);
         testAccount1.Contract_Status__c = 'active' ;
         testAccount1.Account_Status__c = 'Active' ;
         testAccount1.AFrontier_CustomerID__c = '5605846';
         
         testAccount2.Renewal_Date__c = myFutureDate ;
         
         AccountList.clear();
         AccountList.add(testAccount1);
         AccountList.add(testAccount2);
         
        
         update AccountList;
         system.debug('AccountList' + AccountList);
         
        Test.startTest();
        AccountTypeUpdate  testJob = new AccountTypeUpdate();
        testJob.query = 'SELECT id,Ownerid, name, Type__c, AFrontier_CustomerID__c, Renewal_Date__c, Account_Status__c, Contract_Status__c from Account where recordtypeid =\'' + AccountRecordType + '\' and AFrontier_CustomerID__c != null and Renewal_Date__c != null limit 10'; 
        Id batchsid  = Database.executeBatch(testJob);
        Test.stopTest();
        
        AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id = :batchsid];        
        System.debug('\n\nFinal results are: '+a);        
        System.AssertEquals('Completed', a.status);        
        //System.AssertEquals(0, a.NumberOfErrors);
        }

}